﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using LearnNet.BLL;
using System.Xml;
using LearnNet.Common;
using System.Drawing;
using System.Reflection;
using System.Threading;
using System.Collections;
using mshtml;
using LearnNet.Forum;
using LearnNet.Entity;
using System.Runtime.InteropServices;
using System.Net;

using System.Collections;
using System.Configuration;
using System.Data;

namespace BBSReport
{
    
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
        }
        private XmlHelper xmlHelper = new XmlHelper(string.Concat(Application.StartupPath, "/config.xml"));
        public System.Windows.Forms.Timer timer1 = new System.Windows.Forms.Timer();
        public System.Windows.Forms.Timer timer2 = new System.Windows.Forms.Timer();
        private List<SiteInfoEntity> SiteInfos = new List<SiteInfoEntity>();//要发送的列表
        private List<ReportListEntity> ReportLists = new List<ReportListEntity>();
        private List<ReportContentEntity> ReportContentList = new List<ReportContentEntity>();
        private RecordCookie recordCookie = new RecordCookie();
        private int state =-1;
        private int stateReport = 0;
        private bool isStop = false;
        private int siteIndex = 0;
        private int reportIndex = 0;
        private string pageCollect = string.Empty;//当前采集第一页
        private int siteCollectNum = 0;
        private void Main_Load(object sender, EventArgs e)
        {
            //this.webBrowser1.Navigating += new WebBrowserNavigatingEventHandler(webBrowser1_Navigating);
           // this.webBrowser1.Navigated += new WebBrowserNavigatedEventHandler(webBrowser1_Navigated);
            this.webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
           // this.webBrowser1.NewWindow += new CancelEventHandler(webBrowser1_NewWindow);
            timer1.Tick += new EventHandler(timer_Tick1);
            timer1.Interval = 1000;
            timer1.Enabled = false;
            timer2.Tick += new EventHandler(timer_Tick2);
            timer2.Interval = 1000;
            timer2.Enabled = false;
        }

        #region  下拉按钮
        private void 添加发送内容ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmAddContent fm = new frmAddContent();
            fm.ShowDialog();
        }

        private void 发送站点维护ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmAddSite fm = new frmAddSite();
            fm.ShowDialog();
        }

        private void 用户维护ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmAddUser fm = new frmAddUser();
            fm.ShowDialog();
        }

        private void 登录采集维护ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmLogin fm = new frmLogin();
            fm.ShowDialog();
        }


        private void 发表回帖ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmReport fm = new frmReport();
            fm.ShowDialog();
        }
        #endregion 

#region  cookies

        [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool InternetSetCookie(string lpszUrlName, string lbszCookieName, string lpszCookieData);

         
#endregion
        #region 工具栏
        private void tlSbtnStart_Click(object sender, EventArgs e)
        {
            QueryParam qp=new QueryParam();
            qp.PageIndex=1;
            qp.PageSize=1000;
            qp.Where = "enable=1";
            int recordNum=0;
            SiteInfos = BLLHelper.SiteInfoList(qp, out recordNum);
            tlssLbSiteInfo.Text = "共发送站点" + SiteInfos.Count.ToString() + "个";
            tlsBtnStop.Enabled = true;
            tlsBtnUp.Enabled = true;
            tlsBtnNext.Enabled = true;
            tlsBtnNextSite.Enabled = true;
            tlSbtnStart.Enabled = false;
            timer1.Enabled = true;
            state = -1;
            siteIndex = Utils.StringToInt(tlsTbSiteIndex.Text,0) ;
        }


        private void tlsBtnStop_Click(object sender, EventArgs e)
        {
            tlsBtnUp.Enabled = false;
            tlsBtnNext.Enabled = false;
            tlsBtnNextSite.Enabled = false;
            tlsBtnStop.Enabled = false;
            tlsGoOn.Enabled = true;
           isStop=true;
           if (state != -1)
           {
               timer1.Enabled = false;
           }
           else
           {
               timer2.Enabled = false;
           }
           
        }

        private void tlsGoOn_Click(object sender, EventArgs e)
        {
            tlsBtnStop.Enabled = true;
            tlsGoOn.Enabled = false;
            tlsBtnUp.Enabled = true;
            tlsBtnNext.Enabled = true;
            tlsBtnNextSite.Enabled = true;
            isStop = false;
            if (state != -1)
            {
                timer1.Enabled = true;
            }
            else
            {
                timer2.Enabled = true;
            }
        }
        private void tlsBtnUp_Click(object sender, EventArgs e)
        {
            if (reportIndex > 0)
            {
                MessageBox.Show("已经是第一篇帖子了");
            }
            else
            {
                reportIndex--;
            }
        }

        private void tlsBtnNext_Click(object sender, EventArgs e)
        {
            if (reportIndex > ReportLists.Count-1)
            {
                MessageBox.Show("已经是最后一篇帖子了");
            }
            else
            {
                reportIndex++;
            }
        }

        private void tlsNextSite_Click(object sender, EventArgs e)
        {
            if (siteIndex > SiteInfos.Count - 1)
            {
                MessageBox.Show("已经最后一个站点了");
            }
            else
            {
                MessageBox.Show("下一个站点");
                siteIndex++;
                state = -1;
                timer2.Enabled = false;
                reportIndex = ReportLists.Count;
                timer1.Enabled = true;

            }
        }

        #endregion 

        protected void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (e.Url.ToString() != webBrowser1.Url.ToString())
                return;
            if (webBrowser1.ReadyState.ToString() == WebBrowserReadyState.Complete.ToString())
            {

               // this.webBrowser1.Document.Window.Error += new HtmlElementErrorEventHandler(Window_Error);

                if (state == -1)
                {
                    timer1.Enabled = false;
                }
                else
                {
                    if (timer2.Enabled != true)
                    {
                        timer1.Interval = 1000;
                        timer1.Enabled = true;
                    }
                    

                }
                if (stateReport != 1)
                {
                    if (timer1.Enabled != true)
                    {
                        timer2.Enabled = true;
                        timer2.Interval = 1000;
                    }
                }

            }
        }

        public void timer_Tick1(object sender, EventArgs e)
        {
           
           
            timer2.Enabled = false;
            stateReport = 0;
            string str = string.Empty;
            //UpdateInfo upInfo = new UpdateInfo();
            //upInfo.Count = dt.Rows.Count;
            //upInfo.Index = 0;
            string strSql = string.Empty;

            string strMessage = string.Empty;
            if (isStop == true)
            {
                timer1.Enabled = false;
               
                return;
            }
            if (siteIndex > SiteInfos.Count - 1)
            {
                timer1.Enabled = false;

                tlSbtnStart.Enabled = true;
                tlsGoOn.Enabled = false;
                tlsBtnStop.Enabled = false;
                tlssLbState.Text = "发送完毕";
                return;
            }
            tlssLbSiteInfo.Text = "共发送站点" + SiteInfos.Count.ToString() + "个,当前第" + (siteIndex + 1).ToString() + "个" ;
            try
            {

                switch (state)
                {
                    case -1:
                        {
                            timer1.Enabled = false;
                            tlssLbState.Text = "正在采集文章列表";
                            state = 0;
                            string siteUrl = "http://";
                            siteUrl = string.Concat(siteUrl, SiteInfos[siteIndex].SiteUrl);
                            int collectListNum = 0;//采集列表数量
                            string collectListUrl = xmlHelper.GetAttribute("root/station[@url='" + SiteInfos[siteIndex].SiteUrl + "']/urlList", "url");
                            string collectInWord = xmlHelper.GetAttribute("root/station[@url='" + SiteInfos[siteIndex].SiteUrl + "']/urlCollect", "InWord");
                            collectListNum = Utils.StringToInt(xmlHelper.GetAttribute("root/station[@url='" + SiteInfos[siteIndex].SiteUrl + "']/urlList", "count"), 0);
                            string strEncoding = xmlHelper.GetAttribute("root/station[@url='" + SiteInfos[siteIndex].SiteUrl + "']", "encoding");

                            CollectData clData = new CollectData();
                            for (int i = 1; i <= collectListNum; i++)
                            {
                                try
                                {
                                    if (i == 1)
                                    {
                                        pageCollect = string.Concat(siteUrl, "/", collectListUrl.Replace("$0", i.ToString()));
                                    }
                                    string strRequest = Utils.GetRequestString(string.Concat(siteUrl, "/", collectListUrl.Replace("$0", i.ToString())), 12000, 0, Encoding.GetEncoding(strEncoding));
                                    clData.GetLinkHref(strRequest, collectInWord, siteUrl);

                                }
                                catch (Exception ex)
                                {
                                    MessageBox.Show(ex.Message);
                                }

                            }
                            tlssLbState.Text = "正在采集完成文章列表";
                            tlssLbState.Text = "文章列表正在插入数据库";
                            if (clData.getLinksInfo.Pages.Values.Count == 0)
                            {
                                state = -1;

                                siteCollectNum++;
                                timer1.Enabled = true;
                               // MessageBox.Show("meiyou用户");
                                if (siteCollectNum >2)
                                {
                                    siteIndex++;
                                    siteCollectNum = 0;
                                }
                                return;
                            }
                            foreach (LearnNet.Entity.CollectPageInfo pageInfo in clData.getLinksInfo.Pages.Values)
                            {
                                if (BLLHelper.ReportListDisp(pageInfo.Url.Replace("http://", "")).Url == "")
                                {
                                    ReportListEntity reportList = new ReportListEntity();
                                    reportList.Adddate = DateTime.Now;
                                    reportList.DataTable_Action_ = DataTable_Action.Insert;
                                    reportList.IsSend = "0";
                                    reportList.Type = SiteInfos[siteIndex].Id;
                                    reportList.Url = pageInfo.Url;
                                    BLLHelper.ReportListInsertUpdateDelete(reportList);

                                }
                            }
                            tlssLbState.Text = "文章列表插入数据库完成";
                            timer1.Enabled = true;
                          
                            break;
                        }
                    case 0:
                        {
                            timer1.Enabled = false;
                            webBrowser1.Url = new Uri(xmlHelper.GetAttribute("root/station[@url='" + SiteInfos[siteIndex].SiteUrl + "']/logout", "url"));
                            state = 1;
                            timer1.Enabled = true;
                            timer1.Interval = 14000;
                            tlssLbState.Text = "正在登出";
                            break;
                        }

                    case 1:
                        {
                            timer1.Enabled = false;
                            webBrowser1.Url=new Uri(xmlHelper.GetAttribute("root/station[@url='" + SiteInfos[siteIndex].SiteUrl + "']/login", "url"));
                            state = 2;
                            tlssLbState.Text = "正在打开登录页面";

                            timer1.Interval = 14000;
                            timer1.Enabled = true;
                            break;
                        }
                    case 2:
                        {
                            timer1.Enabled = false;
                            tlssLbState.Text = "正在登录";
                            UserInfoEntity userInfo = new UserInfoEntity();
                            QueryParam qp = new QueryParam();
                             int recordNum=0;
                            qp.PageSize = 1;
                            qp.PageIndex = 1;
                            qp.Where = "type='" + SiteInfos[siteIndex].Id.ToString() + "' ";
                            List<UserInfoEntity> userLists = BLLHelper.UserInfoList(qp, out recordNum);
                            if (recordNum > 0)
                            {
                                string strReturn = string.Empty;
                                if (!ReportHelper.SetAttribute("root/station[@url='" + SiteInfos[siteIndex].SiteUrl + "']/login/name", userLists[0].Name , webBrowser1, xmlHelper))
                                {
                                    strReturn += "名称设置出错!";
                                }
                                if (!ReportHelper.SetAttribute("root/station[@url='" + SiteInfos[siteIndex].SiteUrl + "']/login/pwd", userLists[0].Pwd, webBrowser1, xmlHelper))
                                {
                                    strReturn += "密码设置出错!";
                                }
                                //if (xmlHelper.GetNode("root/station[@url='" + SiteInfos[siteIndex].SiteUrl + "']/login/checkbox") != null)
                                //{
                                //    if (!ReportHelper.SetAttribute("root/station[@url='" + SiteInfos[siteIndex].SiteUrl + "']/login/checkbox", "true", webBrowser1, xmlHelper))
                                //    {
                                //        strReturn += "保存密码设置出错!";
                                //    }
                                //}
                                try
                                {
                                    object obj = null;
                                    if (string.IsNullOrEmpty(xmlHelper.GetAttribute("root/station[@url='" + SiteInfos[siteIndex].SiteUrl + "']/login/button", "key")))
                                    {
                                        if (!string.IsNullOrEmpty(xmlHelper.GetAttribute("root/station[@url='" + SiteInfos[siteIndex].SiteUrl + "']/login/form", "index")))
                                        {
                                            obj = webBrowser1.Document.Forms[Utils.StringToInt(xmlHelper.GetAttribute("root/station[@url='" + SiteInfos[siteIndex].SiteUrl + "']/login/form", "index"), 0)].InvokeMember("submit");
                                        }
                                        else
                                        {
                                            strReturn += "xml配置错误";
                                        }
                                    }
                                    else
                                    {
                                        obj = webBrowser1.Document.GetElementById(xmlHelper.GetAttribute("root/station[@url='" + SiteInfos[siteIndex].SiteUrl + "']/login/button", "key")).InvokeMember("click");
                                    }

                                  
                                    reportIndex = 0;
                                    tlssLbState.Text = "登录成功";
                                    qp.PageIndex = 1;
                                    qp.PageSize = int.MaxValue;
                                    qp.Where = " type=" + SiteInfos[siteIndex].Id + " and issend=0";
                                    tlssLbState.Text = "正在获取文章列表和发送内容";
                                    ReportLists = BLLHelper.ReportListList(qp, out recordNum);
                                    qp.PageIndex=1;
                                    qp.Where=" type='"+SiteInfos[siteIndex].Id+"' or type='0' ";
                                    ReportContentList = BLLHelper.ReportContentList(qp, out recordNum);
                                    tlssLbState.Text = "获取文章列表和发送内容成功";
                                    tlssLbReportList.Text = SiteInfos[siteIndex].SiteUrl + "共有发送列表" + ReportLists.Count + "个";
                                    timer2.Interval = 7000;
                                    timer2.Enabled = true;
                                  
                                }
                                catch (Exception ex)
                                {

                                    strReturn += ex.Message;
                                    state = -1;
                                    timer1.Enabled = true;
                                    MessageBox.Show(ex.Message);

                                }
                                finally
                                {
                                   
                                   
                                }
                                strMessage = strReturn + strMessage;
                            }
                            else
                            {//没有用户
                                siteIndex++;
                                state = -1;
                                timer1.Enabled = true;
                                MessageBox.Show("meiyou ");
                            }

                            break;
                        }

                  

                }

            }
            catch (Exception ex)
            {
                //没有用户
                siteIndex++;
                if (siteIndex > SiteInfos.Count - 1)
                {
                    timer2.Enabled = false;
                }
                   
                else
                {
                    state = -1;
                    timer1.Enabled = true;
                }
                strMessage = strMessage + ex.Message;
                MessageBox.Show(strMessage);
            }


         

        }

        public void timer_Tick2(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            state = -1;
            // this.webBrowser1.Document.Click += new HtmlElementEventHandler(Document_Click);
            string str = string.Empty;
            //UpdateInfo upInfo = new UpdateInfo();
            //upInfo.Count = dt.Rows.Count;
            //upInfo.Index = 0;
            string strSql = string.Empty;
            string strMessage = string.Empty;
            if (isStop == true)
            {
                timer2.Enabled = false;
                return;
            }
            if (reportIndex > ReportLists.Count - 1)
            {
                timer2.Enabled = false;
                stateReport = 0;
                timer1.Enabled = true;
                siteIndex++;
                //MessageBox.Show("reportindex>");
                return;
                
            }
            tlssLbReportIndex.Text = "当前发送" + SiteInfos[siteIndex].SiteUrl + "第" + (reportIndex + 1).ToString() + "个";
            tlssLbState.Text = "正在发送文章";
            try
            {

                switch (stateReport)
                {
                    case 0:
                        {
                            timer2.Enabled = false;
                            //webBrowser1.Navigate(ReportLists[reportIndex].Url);

                            //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ReportLists[reportIndex].Url);

                            //request.CookieContainer = new CookieContainer();

                            //request.CookieContainer.SetCookies(webBrowser1.Url, webBrowser1.Document.Cookie);

                            //if (recordCookie.StrCookie != webBrowser1.Document.Cookie)
                            //{
                            //    recordCookie.StrCookie = webBrowser1.Document.Cookie;
                            //}
                           // InternetSetCookie(ReportLists[reportIndex].Url, ReportLists[reportIndex].Url, webBrowser1.Document.Cookie);
                           
                            webBrowser1.Url=new Uri(ReportLists[reportIndex].Url);//, "", System.Text.Encoding.Default.GetBytes(webBrowser1.Document.Cookie), "Cookie");
                            stateReport = 1;
                           
                            tlssLbState.Text = "打开发送地址";
                            webBrowser1.Document.Body.ScrollTop = webBrowser1.Document.Body.ScrollRectangle.Height;
                            timer2.Enabled = true;
                            timer2.Interval = Utils.StringToInt(xmlHelper.GetAttribute("root/station[@url='" + SiteInfos[siteIndex].SiteUrl + "']", "time"), 15000);
                            break;
                        }

                    case 1:
                        {
                            timer2.Enabled = false;
                            tlssLbState.Text = "正在发送";
                            int rContentIndex = 0;
                            Random rdm = new Random();
                            rContentIndex = rdm.Next(ReportContentList.Count - 1);
                            
                            stateReport = 2;
                            timer2.Interval = 8000;// Utils.StringToInt(xmlHelper.GetAttribute("root/station[@url='" + SiteInfos[siteIndex].SiteUrl + "']", "time"), 15000);
                            if (!ReportHelper.SetAttribute("root/station[@url='" + SiteInfos[siteIndex].SiteUrl + "']/report/content", ReportContentList[rContentIndex].SendContent, webBrowser1, xmlHelper))
                            {
                              //  MessageBox.Show("发送设置出错!");
                            }


                            try
                            {
                                object obj = null;
                                if (string.IsNullOrEmpty(xmlHelper.GetAttribute("root/station[@url='" + SiteInfos[siteIndex].SiteUrl + "']/report/button", "key")))
                                {
                                    if (!string.IsNullOrEmpty(xmlHelper.GetAttribute("root/station[@url='" + SiteInfos[siteIndex].SiteUrl + "']/report/form", "index")))
                                    {
                                        obj = webBrowser1.Document.Forms[Utils.StringToInt(xmlHelper.GetAttribute("root/station[@url='" + SiteInfos[siteIndex].SiteUrl + "']/report/form", "index"), 0)].InvokeMember("submit");
                                    }
                                    else
                                    {
                                        //  MessageBox.Show("xml发送配置错误");
                                    }
                                }
                                else
                                {
                                    obj = webBrowser1.Document.GetElementById(xmlHelper.GetAttribute("root/station[@url='" + SiteInfos[siteIndex].SiteUrl + "']/report/button", "key")).InvokeMember("click");
                                }



                                tlssLbState.Text = "发送成功";
                            }
                            catch (Exception ex)
                            {

                               // MessageBox.Show(ex.Message);

                            }
                            finally
                            {

                                try
                                {
                                    tlssLbState.Text = "更新发送数据库";
                                    ReportListEntity reportList = ReportLists[reportIndex];
                                    reportList.SendDate = DateTime.Now;
                                    reportList.DataTable_Action_ = DataTable_Action.Update;
                                    reportList.IsSend = "1";
                                    BLLHelper.ReportListInsertUpdateDelete(reportList);
                                }
                                catch (Exception ex)
                                {
                                   // MessageBox.Show(ex.Message);
                                    reportIndex++;
                                }

                                timer2.Enabled = true;

                            }
                            break;
                        }
                    case 2:
                        {
                            timer2.Enabled = false;
                            webBrowser1.Url = new Uri(pageCollect);
                            reportIndex++;
                            stateReport = 0;
                            timer2.Interval = 7000;
                            timer2.Enabled = true;
                            break;
                        }

                }

            }
            catch (Exception ex)
            {
                stateReport = 0;
                reportIndex++;
                timer2.Enabled = true;
                strMessage += ex.Message;
              //  MessageBox.Show(strMessage);
            }

        }



    }

    /// <summary>
    /// cookie记录类
    /// </summary>
    public class RecordCookie
    {
        public string StrCookie { get; set; }
        public int Index { get; set; }
    }
}
